package com.product.timeTask;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: TimeTask
 * @date: 2021/3/25
 * @author: 王瑾
 */
@Slf4j
@Component
public class TimeTask {

    @Resource
    private JdbcTemplate jdbcTemplate; // springboot集成mybatis-spring-boot-starter后本身封装的工具类

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 定时刷新redis里面的基础数据
     */
    @Scheduled(cron = "0 0 2 * * ?")  // 每俩个小时执行
    public void execute() {
        log.info("==================定时任务开始======================");
        String sql = "SELECT * FROM basic_must ";
//        String sql2 = "SELECT * FROM basic_coal ";
        List<Map<String, Object>> mapsList = jdbcTemplate.queryForList(sql);
//        List<Map<String, Object>> maps2List = jdbcTemplate.queryForList(sql2);
        Map<String, List<Map>> deviceMap = mapsList.stream().collect(Collectors.groupingBy(map->{
            Map result = map;
            if("".equals(String.valueOf(result.get("type")))){
                return "OTHER";
            }else{
                return String.valueOf(result.get("type"));
            }
        }));
        for(String key: deviceMap.keySet()){
            redisTemplate.opsForValue().set(key, deviceMap.get(key));
        };
        log.info("==================定时任务结束======================");
    }
}
